<template>
  <div class="main-menu">
    <div class="logo">
      <img class="img" src="@/assets/img/logo.svg" alt="" />
      <h2 class="title" v-show="!isFold">homed</h2>
    </div>
    <div class="menu">
      <el-menu
        :collapse="isFold ? true : false"
        :default-active="defaultActive"
        text-color="#b7bdc3"
        active-text-color="#fff"
        background-color="#001529"
      >
        <template v-if="userMenus && userMenus.length > 0">
          <template v-for="item in userMenus" :key="item.id">
            <el-sub-menu :index="item.id + ''">
              <template #title>
                <!-- 字符串el-icon-moniter  => 使用动态组件 -->
                <el-icon>
                  <component :is="item.icon?.split('el-icon-')[1]" />
                </el-icon>
                <span>{{ item.name }}</span>
              </template>
              <template v-for="subItem in item.children" :key="subItem.id">
                <el-menu-item :index="subItem.id + ''" @click="handleItemClick(subItem)">
                  {{ subItem.name }}
                </el-menu-item>
              </template>
            </el-sub-menu>
          </template>
        </template>
      </el-menu>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import useLoginStore from '@/store/login/login'
import { useRoute, useRouter } from 'vue-router'
import { mapMenusToPermissions } from '@/utils/map-menus'

defineProps({
  isFold: {
    type: Boolean,
    default: false
  }
})

// 1. 获取动态菜单
const loginStore = useLoginStore()
const userMenus = loginStore.userMenus

// 2. 点击菜单项
const router = useRouter()
function handleItemClick(item) {
  const url = item.url
  router.push(url)
}

// 3. EL-menu默认菜单
const route = useRoute()

// 配合面包屑跳转修改
const defaultActive = computed(() => {
  const pathMenu = mapMenusToPermissions(route.path, userMenus)
  return pathMenu ? pathMenu.id + '' : '1'
})
</script>

<style lang="less" scoped>
.main-menu {
  height: 100%;
  background-color: #001529;
  .logo {
    display: flex;
    height: 28px;
    padding: 12px 10px 8px 10px;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    overflow: hidden;
    .img {
      height: 100%;
      margin: 0 10px;
    }
    .title {
      font-size: 16px;
      font-weight: 600;
      color: #fff;
      white-space: nowrap;
    }
  }
}
.el-menu {
  border-right: none;
  user-select: none;
}
.el-sub-menu {
  .el-menu-item {
    padding-left: 50px !important;
    background-color: #001529;
  }
  .el-menu-item:hover {
    color: #0a60bd;
  }
  .el-menu-item.is-active {
    color: #0a60bd;
  }
}
</style>
